﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace NET6Demo.WebApi.Utility.Filters
{
    /// <summary>
    /// ActionFilter扩展定制
    /// </summary>
    public class CustomLogActionFilterAttribute : Attribute, IActionFilter
    {

        private readonly ILogger<CustomLogActionFilterAttribute> _logger;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public CustomLogActionFilterAttribute(ILogger<CustomLogActionFilterAttribute> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 在XX执行Action执行之后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var controllerName = context.RouteData.Values["controller"];
            var actionName = context.RouteData.Values["action"];

            _logger.LogInformation($"在{controllerName}--{actionName} 执行之后====");
            //这里是执行完API之后，在这里执行业务逻辑---这里可以记录计算结果
            Console.WriteLine("CustomActionFilterAttribute.OnActionExecuted");
        }

        /// <summary>
        ///  在XXAction执行之前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var controllerName = context.RouteData.Values["controller"];
            var actionName = context.RouteData.Values["action"];

            _logger.LogInformation($"在{controllerName}--{actionName} 执行之前====");
            //这里是执行完API之前，在这里执行业务逻辑--这可以记录参数
            Console.WriteLine("CustomActionFilterAttribute.OnActionExecuting");
        }
    }
}
